//
// Copyright (c) 2014, 保留所有权利。
//
// FollowRecordHandler.java
//
// 作    者：王红燕
// 当前版本：1.0
// 2015年4月17日 上午10:49:50
//
// 
//
package com.common.api.handler;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.vanke.agent.bean.FollowRecord;
import com.vanke.agent.bean.FollowRecordMessage;
import com.vanke.agent.common.FollowRecordUtil;
import com.vanke.agent.common.log.LoggerUtil;

/**
 * @author 王红燕
 *
 */
public class FollowRecordHandler extends ApiHandler {	
	static Logger log = LoggerUtil.getLoggerByName("api_invoke");

	/* (non-Javadoc)
	 * @see com.common.api.handler.ApiHandler#handle(net.sf.json.JSONObject)
	 */
	@Override
	public JSONObject handle(JSONObject json) {
		log.info("handle followRecord: " + json);

		String fieldCstGUID = "cstGUID";
		
		if (!json.containsKey(fieldCstGUID)) {
			return genErr(1001, "缺少必须参数[" + fieldCstGUID + "]");
		}
		long cstGUID = 0;
		try {
			cstGUID = json.getLong(fieldCstGUID);
		} catch (Exception e) {
			log.error(e);
			if (e.getMessage() != null && e.getMessage().contains("is not a number")) {
				return genErr(1002, fieldCstGUID);
			}
			return genErr(1005, "系统处理失败");
		}
		try {
			String oriGUID = FollowRecordUtil.oriGUIDbyCstGUID(cstGUID);
			if (oriGUID == null || oriGUID.trim().equals("")) {
				JSONObject result = getDefResult();
				result.put("list", new ArrayList<FollowRecordMessage>());
				return result;
			}
			//查询跟进
			List<FollowRecord> followRecords = FollowRecordUtil.retrieveFollowRecord(oriGUID);
			if (followRecords.size() > 0) {
				JSONObject result = getDefResult();
				List<FollowRecordMessage> fMessages = FollowRecordUtil.converFollowRecord(followRecords);
				result.put("list", fMessages);
				return result;
			}
			//查询认筹
			followRecords = FollowRecordUtil.retrieveBookingRecord(oriGUID);
			if (followRecords.size() > 0) {
				JSONObject result = getDefResult();
				List<FollowRecordMessage> fMessages = FollowRecordUtil.converFollowRecord(followRecords);
				result.put("list", fMessages);
				return result;
			}
			//查询认购
			followRecords = FollowRecordUtil.retrieveOrderRecord(oriGUID);
			if (followRecords.size() > 0) {
				JSONObject result = getDefResult();
				List<FollowRecordMessage> fMessages = FollowRecordUtil.converFollowRecord(followRecords);
				result.put("list", fMessages);
				return result;
			}
			//查询签约
			followRecords = FollowRecordUtil.retrieveContractRecord(oriGUID);
			if (followRecords.size() > 0) {
				JSONObject result = getDefResult();
				List<FollowRecordMessage> fMessages = FollowRecordUtil.converFollowRecord(followRecords);
				result.put("list", fMessages);
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return genErr(1005, "系统处理失败");
		}
		return genErr(1005, "无任何跟进或成交");
	}

}
